package com.yix.sso.study.cookie.controller;

import com.yix.sso.study.cookie.enums.Const;
import com.yix.sso.study.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    LoginService service;

    @ResponseBody
    @RequestMapping("hello")
    public String hello(){
        return "hello";
    }

    @GetMapping("login")
    public String index(){
        return "login";
    }

    /**
     * 执行登录
     */
    @PostMapping("login")
    @ResponseBody
    public String login(String username, String password, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        return service.doLogin(username.trim(), password.trim(), session, request, response).toJSONString();
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "logout")
    public String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {

        // 保存cookie，实现自动登录
        Cookie cookie_username = new Cookie("cookie_username", "");
        // 删除session里面的用户信息
        session.removeAttribute(Const.SYSTEM_USER_SESSION+cookie_username);
        // 设置cookie的持久化时间，0
        cookie_username.setMaxAge(0);
        // 设置为当前项目下都携带这个cookie
        cookie_username.setPath(request.getContextPath());
        // 向客户端发送cookie
        response.addCookie(cookie_username);

        return "login";
    }
}
